<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{

    public $id;

    CONST ERROR_ACCOUNT_LOCKED = 3;

    public $loginType = 'Front';

    public function authenticate()
    {

        if ($this->loginType == 'Front') {
            $user = ThanhVien::model()->find('ten_tai_khoan=:username', array(':username' => $this->username));
            if (!$user) {
                $this->errorCode = self::ERROR_USERNAME_INVALID;
            } elseif ($user->mat_khau !== md5($this->password)) {
                $this->errorCode = self::ERROR_PASSWORD_INVALID;
            } elseif ($user->status == ThanhVien::ACCOUNT_LOCKED) {
                $this->errorCode = self::ERROR_ACCOUNT_LOCKED;
            } else {
                $this->id = $user->id;
                $auth = Yii::app()->authManager;
                if (!$auth->isAssigned($user->role, $this->id)) {
                    if ($auth->assign($user->role, $this->id)) {
                        Yii::app()->authManager->save();
                    }
                }
                $this->errorCode = self::ERROR_NONE;
//                Yii::app()->user->setState('avatar', $user->avatar);
            }
        }
        if ($this->loginType == 'Back') {

            $user = ThanhVien::model()->find('ten_tai_khoan=:username', array(':username' => $this->username));
            if (!$user)
                $this->errorCode = self::ERROR_USERNAME_INVALID;
            elseif ($user->mat_khau !== md5($this->password)) {
                $this->errorCode = self::ERROR_PASSWORD_INVALID;
            } elseif ($user->status == ThanhVien::ACCOUNT_LOCKED) {
                $this->errorCode = self::ERROR_ACCOUNT_LOCKED;
            } else {
                $this->id = $user->id;
                $auth = Yii::app()->authManager;
                if (!$auth->isAssigned($user->role, $this->id)) {
                    if ($auth->assign($user->role, $this->id)) {
                        Yii::app()->authManager->save();
                    }
                }
                $this->errorCode = self::ERROR_NONE;
//                Yii::app()->user->setState('avatar', $user->avatar);
            }
        }
        return !$this->errorCode;
    }

    public function getId()
    {
        return $this->id;
    }

}